import { ref,computed } from 'vue'
import { defineStore } from 'pinia'
import { ElMessage } from 'element-plus'
import { useUserInfoStore } from '@/stores/user'
import { insertCartAPI ,getCartListAPI,delCartAPI} from '@/apis/cart/cart'



export const useCartStore = defineStore('cart', () => {
    const userStore = useUserInfoStore()

    const isLogin = computed(()=>userStore.userInfo.token)


    const cartList = ref([])

    const updateCartList= async()=>{
        const res = await getCartListAPI(userStore.userInfo.token)
        cartList.value = res.result
    }

    async function mergeCartList(){
        const res = await getCartListAPI(userStore.userInfo.token)
        cartList.value = [...cartList.value,...res.result]
    }

    const add = async(goods) =>{
        const { skuId, count } =goods
        if (isLogin.value){
          await insertCartAPI({ skuId, count })
          updateCartList()
        }else{
            console.log(goods)
            const item = cartList.value.find((item) => goods.skuId == item.skuId)
            if (item) {
                //找到则在原有数量上加1
                item.count = item.count+goods.count
                //否则追加当前的商品
            } else {
                cartList.value.push(goods)
            }
        }
    }

    function singleCheck(skuId,selected){
        const item = cartList.value.find((item) => skuId == item.skuId)
        console.log(item)
        item.selected = selected
        console.log(item.selected)
    }

    function allCheck(selected){
        cartList.value.forEach(item=>item.selected = selected)
    }

    function clearCart(){
        cartList.value = []
    }

    const cartCount = computed(()=>cartList.value.reduce((a,c)=>a + c.count,0))

    const cartAmount = computed(()=>cartList.value.reduce((a,c)=>a + c.count * c.price,0))

    const selectedCount = computed(()=>cartList.value.filter((item)=>item.selected === true).reduce((a,c)=>a + c.count,0))

    const selectedAmount = computed(()=>cartList.value.filter((item)=>item.selected === true).reduce((a,c)=>a + c.count * c.price,0))

    const isAll = computed(()=>cartList.value.every((item)=>item.selected === true))


    const delCart = async(skuId)=>{
        if(isLogin.value){
            await delCartAPI ([skuId])
            updateCartList()
        }else{
            const index = cartList.value.findIndex((item)=>item.skuId == skuId)
            cartList.value.splice(index,1)
        }
        ElMessage.success("删除成功")
    }

    return { cartList, add ,delCart,cartCount,cartAmount,singleCheck,selectedCount,selectedAmount,isAll,allCheck,clearCart,updateCartList,mergeCartList}
}, {

    persist: true,

})
